import 'dart:io';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../theme/font.dart';
import '../world_audio_publish/waveforms_widget.dart';
import '../world_audio_publish/world_audio_publish_page.dart';
import 'picker_image_drag_widget.dart';
import 'picker_video_widget.dart';
import 'world_content_publish_logic.dart';
import 'world_content_publish_state.dart';

/// @description:
/// @author
/// @date: 2024-09-23 16:13:32
class WorldContentPublishPage extends StatefulWidget {
  const WorldContentPublishPage({Key? key}) : super(key: key);

  @override
  State<WorldContentPublishPage> createState() => _WorldContentPublishPageState();
}

class _WorldContentPublishPageState extends State<WorldContentPublishPage> {
  final WorldContentPublishLogic logic = Get.put(WorldContentPublishLogic());

  final WorldContentPublishState state = Get.find<WorldContentPublishLogic>().state;

  @override
  void dispose() {
    Get.delete<WorldContentPublishLogic>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BrnAppBar(title: '发布帖子', backgroundColor: Colors.white),
      backgroundColor: Colors.white,
      body: GetBuilder<WorldContentPublishLogic>(
          init: WorldContentPublishLogic(),
          initState: (_) {},
          builder: (context) {
            return Container(
              color: const Color(0xFFF5FAF9),
              child: SingleChildScrollView(
                child: buildContentImageWerppar(),
              ),
            );
          }),
      bottomNavigationBar: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        margin: EdgeInsets.only(
            top: 30,
            bottom: MediaQuery.of(context).padding.bottom == 0 ? 10 : MediaQuery.of(context).padding.bottom - 10),
        child: GestureDetector(
          onTap: () {
            logic.doPostFeekBack();
            // SnackBaUtils.show();
          },
          child: Container(
            height: 42.h,
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(horizontal: 15),
            margin: const EdgeInsets.symmetric(horizontal: 5),
            decoration:
                BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(21.r)), color: const Color(0xFF25D4D0)),
            child: Text('发布', style: TextStyle(color: Colors.white, fontSize: 15.sp, fontWeight: AppFontWeight.medium)),
          ),
        ),
      ),
    );
  }

  Container buildContentImageWerppar() {
    return Container(
      padding: const EdgeInsets.only(left: 14, right: 14, bottom: 10, top: 10),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 15.w, right: 15.w, bottom: 10),
            decoration:
                BoxDecoration(color: const Color(0xFFF6F6F6), borderRadius: BorderRadius.all(Radius.circular(8.r))),
            child: TextField(
              maxLength: 100,
              focusNode: state.focusNode,
              textInputAction: TextInputAction.done,
              style: TextStyle(color: const Color(0xFF263B38), fontSize: 13.sp, height: 1.5),
              maxLines: 6,
              // controller: _publishState.textController,
              decoration: InputDecoration(
                hintText: '与有趣的Ta相遇吧~',
                hintStyle:
                    TextStyle(color: const Color(0xFF999999), fontSize: 13.sp, fontWeight: AppFontWeight.regular),
                hintMaxLines: 3,
                border: InputBorder.none,
                // counterText: '${_publishState.textController.text.length} / 500'
                // isCollapsed: true,
              ),
              // cursorColor: normalBlackColor,
              onChanged: (value) {
                debugPrint('onChanged--');
                if (value.characters.length >= state.minInputCount) {
                  state.isCanPublish = true;
                } else {
                  state.isCanPublish = false;
                }
                logic.update();
                state.content = value;
                // setState(() {});
                // _publishState.textController.text;
              },
              onEditingComplete: () {
                state.focusNode.unfocus();
              },
            ),
          ),
          const SizedBox(height: 10),
          if (state.publishType == WorldPublishType.image)
            PickerImageDragWidget(
              maxAssets: 9,
              callBack: (assetEntityList) async {
                state.publishType = WorldPublishType.image;
                List<String> filePaths = [];
                for (var assetEntity in assetEntityList) {
                  File? file = await assetEntity.originFile;
                  filePaths.add(file!.path);
                }
                state.filePaths = filePaths;
              },
            ),
          if (state.publishType == WorldPublishType.video)
            PickerVideoWidget(
              callBack: (assetEntity) async {
                state.publishType = WorldPublishType.video;
                if (assetEntity != null) {
                  File? file = await assetEntity.originFile;
                  state.videoPath = file!.path;
                  logic.update();
                }
              },
            ),
          if (state.publishType == WorldPublishType.audio && state.audioPath.isNotEmpty)
            Container(
              color: Colors.transparent,
              height: 50,
              margin: const EdgeInsets.only(bottom: 15),
              child: Row(
                children: [
                  WaveformsWidget(
                    audioPath: state.audioPath,
                    width: 120,
                    padding: EdgeInsets.zero,
                    margin: EdgeInsets.zero,
                    radius: 25,
                  ),
                  const SizedBox(width: 15),
                  GestureDetector(
                    onTap: () {
                      state.publishType = WorldPublishType.image;
                      state.audioPath = '';
                      logic.update();
                    },
                    child: Container(
                        width: 50,
                        height: 50,
                        color: Colors.white,
                        child: Center(child: Image.asset('assets/app/images/world/image_del_icon.png', width: 16.w))),
                  )
                ],
              ),
            ),
          _buildTipsWarpper(),
          _buildPublishTypesWarpper(),
        ],
      ),
    );
  }

  Container _buildPublishTypesWarpper() {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: Row(
        children: [
          Container(
            width: 90,
            height: 30,
            margin: const EdgeInsets.only(right: 12),
            decoration:
                BoxDecoration(color: const Color(0xFFE5F7FF), borderRadius: BorderRadius.all(Radius.circular(15.r))),
            child: BrnIconButton(
                name: '图片',
                direction: Direction.left,
                padding: 4,
                iconWidth: 17,
                style: TextStyle(color: Colors.black, fontSize: 13.sp),
                iconWidget: Image.asset('assets/app/images/world/post_publish_image.png', width: 17),
                onTap: () {
                  state.publishType = WorldPublishType.image;
                  logic.update();
                  PickerImageDragWidgetState.currentInstance()!.showBottomSheet();
                }),
          ),
          Container(
            width: 90,
            height: 30,
            margin: const EdgeInsets.only(right: 12),
            decoration:
                BoxDecoration(color: const Color(0xFFE5FFF2), borderRadius: BorderRadius.all(Radius.circular(15.r))),
            child: BrnIconButton(
                name: '视频',
                direction: Direction.left,
                padding: 4,
                iconWidth: 17,
                style: TextStyle(color: Colors.black, fontSize: 13.sp),
                iconWidget: Image.asset('assets/app/images/world/post_publish_video.png', width: 17),
                onTap: () {
                  state.publishType = WorldPublishType.video;
                  logic.update();
                  Future.delayed(const Duration(milliseconds: 200), () {
                    PickerVideoWidgetState.currentInstance()!.showBottomSheet();
                  });
                }),
          ),
          Container(
            width: 90,
            height: 30,
            decoration:
                BoxDecoration(color: const Color(0xFFFFF1E0), borderRadius: BorderRadius.all(Radius.circular(15.r))),
            child: BrnIconButton(
                name: '音频',
                direction: Direction.left,
                padding: 4,
                iconWidth: 17,
                style: TextStyle(color: Colors.black, fontSize: 13.sp),
                iconWidget: Image.asset('assets/app/images/world/post_publish_audio.png', width: 17),
                onTap: () {
                  Get.bottomSheet(WorldAudioPublishPage(
                    onCallBack: (String audioPath) {
                      state.audioPath = '';
                      logic.update();
                      Future.delayed(const Duration(milliseconds: 200), () {
                        state.audioPath = audioPath;
                        state.publishType = WorldPublishType.audio;
                        logic.update();
                      });
                    },
                  ),
                      isDismissible: false,
                      enableDrag: true,
                      backgroundColor: Colors.transparent,
                      barrierColor: Colors.black.withOpacity(0.2));
                }),
          )
        ],
      ),
    );
  }

  Container _buildTipsWarpper() {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      alignment: Alignment.centerLeft,
      child: Text("""温馨提示：
请勿发布违规内容！
我们支持原创，优质内容会获得更多的推荐机会哦~""", style: TextStyle(color: const Color(0xFF999999), fontSize: 12.sp)),
    );
  }
}
